//
//  AccountViewController.m
//  Hxcsfw
//
//  Created by 企友软mac on 2018/1/17.
//  Copyright © 2018年 企友软mac. All rights reserved.
//

#import "AccountViewController.h"
#import "IAPHelper.h"
#import "IAPProduct.h"
#import "Masonry.h"
#import "LoginViewController.h"
#import "AccountDeatailViewController.h"
#import "AccountViewCell.h"

@interface AccountViewController ()<UITableViewDelegate, UITableViewDataSource, AccountViewCellDelegate> {
    IAPProduct *product;
    UIView *accountVcontent;
    UIView *bgAccountV;
    NSString *strMark;
    NSString *accountMoney;
}

@property (nonatomic, strong) IAPHelper  *m_iapHelper;
@property (nonatomic, strong) NSMutableArray *m_productArray;
@property (weak, nonatomic) IBOutlet UILabel *lbAccount;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation AccountViewController

- (UITableView *)tableView {

    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WSCREENH_WIDTH, WSCREENH_HEIGHT) style:UITableViewStylePlain];

        _tableView.delegate = self;
        _tableView.dataSource = self;
        self.tableView.estimatedRowHeight =0;
        self.tableView.estimatedSectionHeaderHeight =0;
        self.tableView.estimatedSectionFooterHeight =0;
        _tableView.showsVerticalScrollIndicator = YES;
        _tableView.bounces = YES;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {   

    if (!(iPhone5SE) && !(iPhone6_6s) && !(iPhone6Plus_6sPlus) && !(XIPHONE)) {
        return WSCREENH_HEIGHT+ 50;
    }else {
        return WSCREENH_HEIGHT;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *identCell = @"AccountViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identCell];
    if (cell == nil) {
        AccountViewCell *accountViewCell = [[[NSBundle mainBundle] loadNibNamed:@"AccountViewCell" owner:self options:nil] lastObject];

        accountViewCell.lbAccount.text = accountMoney;
        accountViewCell.delegate = self;
        cell = accountViewCell;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }
    return cell;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"账户余额";

    if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].strRemaining]) {
        accountMoney = @"0.00";
    } else {
        if ([[WShareUtil sharedData].strRemaining isEqualToString:@"0"]) {
            accountMoney = @"0.00";
        } else {
            accountMoney = [WShareUtil sharedData].strRemaining;
        }
    }

    [self.view addSubview:self.tableView];

    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"明细查询" forState:UIControlStateNormal];
    [rightBtn.titleLabel setFont:[UIFont systemFontOfSize:12]];
    rightBtn.frame = CGRectMake(0, 0, 60, 30);
    [rightBtn addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBtn2 = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = barBtn2;
    [self loadData];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accoutRefresh:) name:@"AccoutRefresh" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"LoginSuccess" object:nil];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)loginSuccess {
    [self requestWdjf];
}

- (void)accoutRefresh:(NSNotification *)notific {
    NSString *priceChange = notific.object[@"price"];
    NSString *price = accountMoney;
    NSInteger account = [price integerValue] + [priceChange integerValue];
    accountMoney = [NSString stringWithFormat:@"%ld",account];
    [self.tableView reloadData];
}

- (void)rightClick:(UIButton *)btn{
    AccountDeatailViewController *accountDeatailVc = [[AccountDeatailViewController alloc] init];
    accountDeatailVc.title = @"明细查询";
    [self.navigationController pushViewController:accountDeatailVc animated:YES];
}

- (void)btnBuySumClick:(UIButton *)sender {
#if TARGET_IPHONE_SIMULATOR

    [WShareUtil showAlert:@"温馨提示" message:@"请用真机购买"];
    WLog(@"run on simulator");

    return;
#define SIMULATOR_TEST
#else
    //不定义SIMULATOR_TEST这个宏
    product = self.m_productArray[sender.tag];
    WLog(@"%ld",sender.tag);
    WLog(@"%ld",product.m_buyType);
    strMark = [NSString stringWithFormat:@"%ld", (sender.tag + 1)];

    if ([WShareUtil sharedData].dicSession) {

        [self reportSetupOrderInfo:strMark];

    } else {

        [self openIsSelectSheet];
    }

#endif
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 2) {
        return;
    }

    if (buttonIndex == 0) {
        if (![WShareUtil sharedData].dicSession) {
            [SVProgressHUD showImage:nil status:@"请先登录"];
            [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
            [SVProgressHUD dismissWithDelay:1.];
            [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];
            return;
        }
    }

    [IAPHelper sharedData];

    self.m_iapHelper = [IAPHelper new];

    self.m_iapHelper.m_buyType = product.m_buyType;
    [self.m_iapHelper requestProductData];

}

- (void)loadData {
    IAPProduct *product1 = [IAPProduct new];
    product1.m_buyType = ID_Coin1;

    IAPProduct *product2 = [IAPProduct new];
    product2.m_buyType = ID_Coin2;

    IAPProduct *product3 = [IAPProduct new];
    product3.m_buyType = ID_Coin3;

    IAPProduct *product4 = [IAPProduct new];
    product4.m_buyType = ID_Coin4;

    self.m_productArray = [NSMutableArray arrayWithObjects:product1,product2,product3,product4,nil];
}


- (void)openIsSelectSheet {

    bgAccountV = [[UIView alloc] initWithFrame:self.view.bounds];
    bgAccountV.backgroundColor = WRGBAColor(0, 0, 0, 0.5);
    [self.view addSubview:bgAccountV];

    accountVcontent = [[UIView alloc] initWithFrame:CGRectMake((WSCREENH_WIDTH - 280) * 0.5, (WSCREENH_HEIGHT - 240) * 0.5, 280, 235)];
    accountVcontent.backgroundColor = WRGBColor(255, 255, 255);
    accountVcontent.layer.cornerRadius = 10;

    UILabel *lbTit = [[UILabel alloc] initWithFrame:CGRectMake(0, 15, 280, 20)];
    lbTit.backgroundColor = [UIColor whiteColor];
    lbTit.text = @"购买金币";
    lbTit.font = [UIFont systemFontOfSize:16];
    lbTit.textAlignment = NSTextAlignmentCenter;
    [accountVcontent addSubview:lbTit];

    UILabel *lbSubheading1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 45, 280, 20)];
    lbSubheading1.backgroundColor = [UIColor whiteColor];
    lbSubheading1.font = [UIFont systemFontOfSize:14];
    lbSubheading1.text = @"登录掌税通购买:可跨平台使用金币";
    lbSubheading1.textAlignment = NSTextAlignmentCenter;
    [accountVcontent addSubview:lbSubheading1];

    UILabel *lbSubheading2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, 280, 20)];
    lbSubheading2.backgroundColor = [UIColor whiteColor];
    lbSubheading2.font = [UIFont systemFontOfSize:14];
    lbSubheading2.text = @"游客身份购买:仅限本设备使用金币";
    lbSubheading2.textAlignment = NSTextAlignmentCenter;
    [accountVcontent addSubview:lbSubheading2];

    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 99, 280, 1)];
    lineView.backgroundColor = WRGBColor(243, 243, 243);
    [accountVcontent addSubview:lineView];

    UIButton *btnMember = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 280, 44)];
    [btnMember.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btnMember setTitle:@"登录掌税通购买" forState:UIControlStateNormal];
    [btnMember setTitleColor:WRGBColor(46, 141, 238) forState:UIControlStateNormal];
    btnMember.tag = 100;
    [btnMember addTarget:self action:@selector(btnSlecetClick:) forControlEvents:UIControlEventTouchUpInside];
    [accountVcontent addSubview:btnMember];

    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 143, 280, 1)];
    lineView1.backgroundColor = WRGBColor(243, 243, 243);
    [accountVcontent addSubview:lineView1];

    UIButton *btnTourist = [[UIButton alloc] initWithFrame:CGRectMake(0, 144, 280, 44)];
    [btnTourist.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btnTourist setTitle:@"游客身份购买" forState:UIControlStateNormal];
    [btnTourist setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    btnTourist.tag = 110;
    [btnTourist addTarget:self action:@selector(btnSlecetClick:) forControlEvents:UIControlEventTouchUpInside];
    [accountVcontent addSubview:btnTourist];

    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 187, 280, 1)];
    lineView2.backgroundColor = WRGBColor(243, 243, 243);
    [accountVcontent addSubview:lineView2];

    UIButton *btnLogin = [[UIButton alloc] initWithFrame:CGRectMake(0, 188, 280, 44)];
    [btnLogin.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [btnLogin setTitle:@"取消" forState:UIControlStateNormal];
    [btnLogin addTarget:self action:@selector(btnSlecetClick:) forControlEvents:UIControlEventTouchUpInside];
    btnLogin.tag = 120;
    [btnLogin setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [accountVcontent addSubview:btnLogin];

    [self.view addSubview:accountVcontent];

}

- (void)btnSlecetClick:(UIButton *)btn {
    if (btn.tag == 100) {

        [WShareUtil sharedData].Who = @"HYJF";
        LoginViewController *loginVc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVc animated:YES];

    } else if (btn.tag == 110) {
        if ([SKPaymentQueue canMakePayments]) {

            [self reportSetupOrderInfo:strMark];

        } else {

            UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:@"您的手机没有打开程序内付费购买"
                                                               delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];

            [alerView show];
        }
    } else {

    }
    [bgAccountV removeFromSuperview];
    [accountVcontent removeFromSuperview];
}

#pragma mark 创建订单信息
- (void)reportSetupOrderInfo:(NSString *)productId {

    NSString *username;
    NSString *nologinuser = [WShareUtil getUUID];

    NSDictionary *parametersDict;
    if ([WShareUtil sharedData].dicSession) {
        username = [WShareUtil sharedData].dicSession[@"nsrsbh"];
        if (username == nil) {
            username = @"";
        }
        parametersDict = @{@"content":@{@"apptype":@"ios",@"dto":@{@"from":@"recharge",@"productId":productId},@"revert":@"create",@"username":username},@"mode":@"native",@"service":@"order"};
    }else {
        parametersDict = @{@"content":@{@"apptype":@"ios",@"dto":@{@"from":@"recharge",@"productId":productId},@"revert":@"create",@"nologinuser":nologinuser},@"mode":@"native",@"service":@"order"};
    }

    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        WLog(@"------%@",responseObject);
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];
      
        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        if ([successStr isEqualToString:@"true"]) {

            [WShareUtil sharedData].dicOrder = returnDic;

            [WShareUtil sharedData].isShowWait = YES;
            [WShareUtil showWait:YES frame:CGRectMake(0, 32, WSCREENH_WIDTH, WSCREENH_HEIGHT)];

            [IAPHelper sharedData];
            self.m_iapHelper = [IAPHelper new];
            self.m_iapHelper.m_buyType = product.m_buyType;
            WLog(@"%@,%zd",productId, product.m_buyType);
            [self.m_iapHelper requestProductData];

        } else {
            [WShareUtil showAlert:@"温馨提示" message:returnDic[@"errorInfo"]];
            [WShareUtil showWait:NO frame:CGRectZero];
        }

    } failure:^(NSError *error) {
        WLog(@"失败");
        [WShareUtil showWait:NO frame:CGRectZero];
    } showProgress:YES];
}

- (void)requestWdjf{

    NSDictionary *parametersDict;
    NSString *nologinuser;
    if ([WShareUtil sharedData].dicSession) {
        parametersDict = @{@"content":@{@"revert":@"basic",@"username":[WShareUtil sharedData].dicSession[@"nsrsbh"]},@"mode":@"native",@"service":@"mine"};
    } else {
        nologinuser = [WShareUtil getUUID];
        parametersDict = @{@"content":@{@"revert":@"basic",@"nologinuser":nologinuser},@"mode":@"native",@"service":@"mine"};
    }
    NSString *secret = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];
    NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:secret]};


    [WHttpTool POST:[WShareUtil getServerURL:nil] parameters:@{@"params":[CommonFunc encryptWithText:secret]} success:^(id responseObject) {
        NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
        NSString *messageStr = [JsonDic objectForKey:@"message"];
        NSString *successStr = [JsonDic objectForKey:@"success"];

        // 解密请求回的数据（字典）
        NSString *returnStr = [CommonFunc decryptWithText:messageStr];

        // json字符串转字典
        NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

        [WShareUtil sharedData].strRemaining = returnDic[@"remaining"];
        if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].strRemaining]) {
            accountMoney = @"0.00";
        } else {
            if ([[WShareUtil sharedData].strRemaining isEqualToString:@"0"]) {
                accountMoney = @"0.00";
            } else {
                accountMoney = [WShareUtil sharedData].strRemaining;
            }
        }

        [self.tableView reloadData];

    } failure:^(NSError *error) {
        WLog(@"失败");
    } showProgress:YES];
}


@end
